package zone.czh.woi.protocol.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import zone.czh.woi.protocol.protocol.Payload;

/**
 * message Payload{
 *   int64 sn=1;
 *   string cmd=2;
 *   int32 type=3;
 *   bool responseRequired=4;
 *   int64 respondSn=5;
 *   bytes dcn=6;
 *   bytes data=7;
 * }
 */
public class PayloadUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static Object readValue(Payload payload){
        try {
            Object obj = objectMapper.readValue(payload.getData(), Class.forName(new String(payload.getDcn())));
            return obj;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //request
    public static Payload buildPayload(Object obj,boolean responseRequired){
        return buildPayload(obj, Payload.Cmd.REQUEST,responseRequired);
    }
    //request
    public static Payload buildPayload(Object obj,String cmd,boolean responseRequired){
        return buildPayload(obj,cmd, Payload.Type.REQUEST,responseRequired,-1);
    }
    public static Payload buildResponse(Object obj,long respondSn){
        return buildPayload(obj,Payload.Cmd.RESPONSE, Payload.Type.RESPONSE,false,respondSn);
    }
    //response
    public static Payload buildPayload(Object obj,String cmd,long respondSn){
        return buildPayload(obj,cmd, Payload.Type.RESPONSE,false,respondSn);
    }

    public static Payload buildPayload(Object obj,String cmd,int type, boolean responseRequired,long respondSn){
        if (cmd==null){
            return null;
        }
        try {
            return new Payload().setSn(genSn())
                    .setCmd(cmd)
                    .setType(type)
                    .setResponseRequired(responseRequired)
                    .setRespondSn(respondSn)
                    .setDcn(obj.getClass().getName().getBytes())
                    .setData(objectMapper.writeValueAsBytes(obj));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Payload buildHeartbeat(){
        return new Payload().setSn(genSn())
                .setCmd(Payload.Cmd.HEARTBEAT)
                .setType(Payload.Type.REQUEST)
                .setResponseRequired(false);
    }


    public static long genSn(){
        return System.currentTimeMillis();
    }
}
